package controllers

import (
	"comment/models"
)

type LoginController struct {
	BaseController
}

func (c *LoginController) Get() {
	c.TplName = "base/login.html"
}

func (c *LoginController) Post() {
	loginName := c.GetString("name")
	password := c.GetString("password")
	rememberMe := c.GetString("remember")
	if loginName == "" && password == "" {
		c.Redirect("/login", 302)
	}
	if user, ok := models.CheckUserByName(loginName, password); ok != true {
		c.Redirect("/login", 302)
	} else {
		var record models.Record
		record.IP = c.Ctx.Input.IP()
		record.User = &user
		models.AddRecord(&record)
		c.SetSession("userId", user.Id)
		c.SetSession("User", user)
		c.SetSession("Role", models.GetRoleByRoleID(user.Roles))
		c.Ctx.SetCookie("Remember", rememberMe, 31536000, "/")
		c.Redirect("/", 302)
	}
}

func (c *LoginController) Logout() {
	c.SetSession("User", nil)
	c.DelSession("User")
	c.Redirect("/login", 302)
}
